package org.example.fastproject.web.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.fastproject.core.bean.PageParam;
import org.example.fastproject.core.bean.SysUserDetails;
import org.example.fastproject.core.enums.DeletedEnum;
import org.example.fastproject.core.exception.Asserts;
import org.example.fastproject.core.utils.SecurityUtil;
import org.example.fastproject.web.sys.model.SysPermission;
import org.example.fastproject.web.sys.mapper.SysPermissionMapper;
import org.example.fastproject.web.sys.model.SysRolePermission;
import org.example.fastproject.web.sys.model.dto.permission.PermissionInsertDto;
import org.example.fastproject.web.sys.model.dto.permission.PermissionUpdateDto;
import org.example.fastproject.web.sys.model.vo.permission.PermissionVo;
import org.example.fastproject.web.sys.service.SysCacheService;
import org.example.fastproject.web.sys.service.SysPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.fastproject.web.sys.service.SysRolePermissionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 *
 * @author 王海舟
 * @since 2023-01-16 11:54:01
 */
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {

    @Resource
    private SysCacheService cacheService;

    @Resource
    private SysRolePermissionService rolePermissionService;

    @Override
    @Transactional
    public boolean save(PermissionInsertDto dto) {
        String name = dto.getName();
        SysPermission sysPermission = this.getOne(Wrappers.<SysPermission>lambdaQuery()
                .eq(SysPermission::getName,name)
                .ne(SysPermission::getDeleted,DeletedEnum.TRUE.getData()));
        if(Objects.nonNull(sysPermission))
            Asserts.fail("角色名已存在");
        SysUserDetails user = SecurityUtil.getUser();
        sysPermission = BeanUtil.toBean(dto,SysPermission.class);
        sysPermission.setName(name);
        sysPermission.setDescription(dto.getDescription());
        sysPermission.setCreateUser(user.getId());
        sysPermission.setCreateTime(user.getDate());
        sysPermission.setUpdateUser(user.getId());
        sysPermission.setUpdateTime(user.getDate());
        return this.save(sysPermission);
    }

    @Override
    @Transactional
    public boolean remove(Long id) {
        List<Long> userIds = this.getUserIdById(id);
        rolePermissionService.remove(Wrappers.<SysRolePermission>lambdaQuery()
                .eq(SysRolePermission::getPermissionId,id));
        boolean success = this.update(Wrappers.<SysPermission>lambdaUpdate()
                .set(SysPermission::getDeleted, DeletedEnum.TRUE.getData())
                .eq(SysPermission::getId, id));
        if(success){

            if(CollectionUtil.isNotEmpty(userIds)){
                for(Long userId : userIds){
                    cacheService.removePermission(userId);
                }
            }
        }
        return success;
    }

    @Override
    @Transactional
    public boolean update(PermissionUpdateDto dto) {
        String name = dto.getName();
        SysPermission sysPermission = this.getOne(Wrappers.<SysPermission>lambdaQuery()
                .eq(SysPermission::getName,name)
                .ne(SysPermission::getDeleted,DeletedEnum.TRUE.getData())
                .ne(SysPermission::getId,dto.getId()));
        if(Objects.nonNull(sysPermission))
            Asserts.fail("角色名已存在");
        SysUserDetails user = SecurityUtil.getUser();
        sysPermission = BeanUtil.toBean(dto,SysPermission.class);
        sysPermission.setId(dto.getId());
        sysPermission.setDescription(dto.getDescription());
        sysPermission.setUpdateUser(user.getId());
        sysPermission.setUpdateTime(user.getDate());
        boolean success = this.updateById(sysPermission);
        if(success){
            List<Long> userIds = this.getUserIdById(dto.getId());
            if(CollectionUtil.isNotEmpty(userIds)){
                for(Long userId : userIds){
                    cacheService.removePermission(userId);
                }
            }
        }
        return success;
    }

    @Override
    public Page<PermissionVo> page(PageParam param) {
        Page page = new Page(param.getNum(),param.getSize());
        this.page(page);
        List<SysPermission> list =page.getRecords();
        List<PermissionVo> roles = list.stream().map(SysPermission -> {
            return BeanUtil.toBean(SysPermission,PermissionVo.class);
        }).collect(Collectors.toList());
        page.setRecords(roles);
        return page;
    }

    @Override
    public List<String> getByUserId(Long userId) {
        List<String> permissions = cacheService.getPermission(userId);
        if(CollectionUtil.isEmpty(permissions)){
            permissions = this.baseMapper.selectByUserId(userId);
            cacheService.setPermission(userId,permissions);
        }
        return permissions;
    }

    @Override
    public List<Long> getUserIdById(Long permissionId) {
        return this.baseMapper.selectUserIdById(permissionId);
    }
}
